package org.kl.bf.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/*汉字转拼音，转拼音全称和汉子拼音首字母
 * @author muscle_Mo
 * @version ：2012-7-24 下午3:34:18
 *
 */

public class PinYinTranslate {
	/**
	 * 汉字转换位汉语拼音首字母，英文字符不变
	 * 
	 * @param chines
	 *            汉字
	 * @return 拼音
	 * @throws Exception
	 */
	public static String TranslateFirst(String chines) {
		String pinyinName = "";
		String[] temp;
		char[] nameChar = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// UPPERCASE 大写
																	// LOWERCASE小写
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		try {
			for (int i = 0; i < nameChar.length; i++) {
				temp = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
				if (nameChar[i] > 128 && temp != null) {

					pinyinName += temp[0].charAt(0);
				} else {
					pinyinName += nameChar[i];
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pinyinName;
	}

	/**
	 * 汉字转换位汉语拼音全字母，英文字符不变
	 * 
	 * @param chines
	 *            汉字
	 * @return 拼音
	 */
	public static String TranslateFull(String chines) {
		String pinyinName = "";
		char[] nameChar = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);// UPPERCASE 大写
																	// LOWERCASE小写
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < nameChar.length; i++) {
			if (nameChar[i] > 128) {
				try {
					pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pinyinName += nameChar[i];
			}
		}
		return pinyinName;
	}

	public static void main(String[] args) {
		System.out.println(PinYinTranslate.TranslateFull("世纪皇庭"));
	}
}
